package com.yst.gateway.monitor.common.security.extend;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 该过滤器的主要作用就是通过spring著名的IoC生成securityMetadataSource。 
 * securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSourceService。 
 * 该MyInvocationSecurityMetadataSourceService的作用提从数据库提取权限和资源，装配到HashMap中， 
 * 供Spring Security使用，用于权限校验。 
 * @author sparta 11/3/29 
 */
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {  

//	private UrlService urlService;
//	
//	public MySecurityMetadataSource(UrlService urlService){ 
//		this.urlService=urlService;
//        loadResourceDefine();  
//    }  

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;  
	private RequestMatcher pathMatcher;
    public Collection<ConfigAttribute> getAllConfigAttributes() {  
    	return new ArrayList<ConfigAttribute>();
    }  
  
    public boolean supports(Class<?> clazz) {
        return true;  
    }  
    
    //加载所有资源与权限的关系  
    private void loadResourceDefine(){  
		if (resourceMap == null) {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<Map<String, Object>> urlList=null;
			for (Map<String, Object> resource : urlList) {
				String url=resource.get("URL").toString();
				Collection<ConfigAttribute> configAttributes =resourceMap.get(url);
				if(configAttributes==null){
					configAttributes = new ArrayList<ConfigAttribute>();
				}
				configAttributes.add(new SecurityConfig(resource.get("NAME").toString()));
				resourceMap.put("/"+url, configAttributes);
			}
		}
    } 

    //返回所请求资源所需要的权限，即角色集合
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {  
    	Iterator<String> it = resourceMap.keySet().iterator();
		while (it.hasNext()) {
			String resURL = it.next();
			pathMatcher = new AntPathRequestMatcher(resURL);
			if (pathMatcher.matches(((FilterInvocation) object).getRequest())) {
				Collection<ConfigAttribute> returnCollection = resourceMap
						.get(resURL);
				return returnCollection;
			}
		}
		return null;
    }  
      
}  